<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//车牌
class Chepai extends MY_Controller {

	function __construct(){
		
		parent::__construct();
		
	}

	//start
	/**
	* @name 获取车牌列表
	* @return 
	*/
	//end
	function get_list(){
		$user_id = $this->user_id;

		$this->load->dmodel('m_chepai','chepai');
		$this->load->model('User/UserModel','UserModel');
		
		$user = $this->UserModel->get_info($user_id);
		
		$list = $this->chepai->getAll("user_id='{$user_id}'");
		foreach($list as $key=>$val){
			$list[$key]['default'] = 0;
			if($val['id']==$user['chepai_id']){
				$list[$key]['default'] = 1;
			}
		}
		$this->data_out($list);
	}
	
	//start
	/**
	* @name 添加车牌
	* @param chepai false char 车牌
	* @return 
	*/
	//end
	function add(){
		$user_id = $this->user_id;
		
		$chepai = $this->input->post('chepai',null,'');
		
		if(!preg_match('/^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/u',$chepai)){
			$this->err_out("请输入正确的车牌");
		}
		
		$arr = array(
			'chepai'=>$chepai
		);
		
		foreach($arr as $key=>$val){
			if($val===''){
				unset($arr[$key]);
			}
		}
		if(count($arr)<=0){
			$this->err_out("请输入正确的数据");
		}
		$time = time();
		
		$arr['user_id'] = $user_id;
		$arr['addtime'] = $time;

		$this->load->dmodel('m_chepai','chepai');
		
		$is_exist = $this->chepai->where_exist(array('user_id'=>$user_id,'chepai'=>$arr['chepai']));
		if($is_exist){
			$this->err_out('不能添加重复的车牌');
		}
		$count = $this->chepai->getCount("user_id='{$user_id}'");
		if($count>5){
			$this->err_out('不能添加超过5个车牌');
		}
		
		
		$chepai_id = $this->chepai->add($arr);
		
		
		
		if($count==0){
			$this->load->model('User/UserModel','UserModel');
			$this->UserModel->edit(array('chepai_id'=>$chepai_id),"id='{$user_id}'");
		}
		
		
		$this->data_out($arr);
	}

	//start
	/**
	* @name 切换车牌
	* @param id false char 车牌id
	* @return 
	*/
	//end
	function change(){
		$user_id = $this->user_id;
		
		$id = $this->input->post('id',null,0);
		
		$this->load->dmodel('m_chepai','chepai');
		
		$info = $this->chepai->_id_get_info($id);
		if(!$info){
			$this->err_out("数据不存在");
		}

		if($info['user_id'] != $user_id){
			$this->err_out("数据不存在");
		}
		
		$this->load->model('User/UserModel','UserModel');
		$this->UserModel->edit(array('chepai_id'=>$id),"id='{$user_id}'");
		
		$this->data_out(1);
	}
	
	//start
	/**
	* @name 删除车牌
	* @param id true int 车牌id
	* @return 
	*/
	//end
	function del(){
		$user_id = $this->user_id;
		
		$id = $this->input->post('id',null,0);
		
		$this->load->dmodel('m_chepai','chepai');
		
		$info = $this->chepai->_id_get_info($id);
		if(!$info){
			$this->err_out("数据不存在");
		}

		if($info['user_id'] != $user_id){
			$this->err_out("数据不存在");
		}
		
		$this->load->model('User/UserModel','UserModel');
		$user = $this->UserModel->get_info($user_id);
		if($id==$user['chepai_id']){
			$this->err_out("该车牌正在使用中");
		}
		
		
		$this->chepai->del("id='{$id}'");
		
		$this->data_out(1);
	}
}
